package ar.com.photo_admin.taglibs
import ar.com.photo_admin.domain.*;

class CustomSecurityTagLib {
	
	def springSecurityService
	
	def isAdmin = { attrs, body ->
		User user = springSecurityService.getCurrentUser()
		
		if (user.hasRole(Role.ROLE_ADMIN)) {
			out << body()
		}
	}
	
	def isEventOwner = { attrs, body ->
		Event event = Event.get(attrs.eventId)
		User user = springSecurityService.getCurrentUser()
				
		if (event.photographer == user || user.hasRole(Role.ROLE_ADMIN)) {
			out << body()
		}
	}
	
	def isEventClientOrOwner = { attrs, body ->
		Event event = Event.get(attrs.eventId)
		User user = springSecurityService.getCurrentUser()
		
		if (event.photographer == user || event.client == user || user.hasRole(Role.ROLE_ADMIN)) {
			out << body()
		}
	}
	
	def isEventAllowed = { attrs, body ->
		Event event = Event.get(attrs.eventId)
		
		def allowedUsersList = []
		allowedUsersList.add(event.photographer)
		allowedUsersList.add(event.client)
		event.albums.each {
			allowedUsersList.addAll(it.getUsersWhoCanAccess())
		}

		if (allowedUsersList.contains(springSecurityService.getCurrentUser())) {		
			out << body()
		}
	}
	
	def isAlbumAllowed = { attrs, body ->				
		EventAlbum album = EventAlbum.get(attrs.albumId)
		if (album == null) {
		 	//El album no existe, lo esta creando.
			out << body()			
		}
		else {
			// El album existe. Se fija en quienes tienen permiso para  visualizarlo.
						
			def allowedUsersList = []
			allowedUsersList.add(album.event.photographer)
			allowedUsersList.add(album.event.client)
			allowedUsersList.addAll(album.getUsersWhoCanAccess())
			
			if (allowedUsersList.contains(springSecurityService.getCurrentUser())) {
				out << body()
			}
		}		
	}
	
	def isPurchaseOrderAllowed = { attrs, body ->
		PurchaseOrder order = PurchaseOrder.get(attrs.orderId)
		
		def allowedUsersList = []
		allowedUsersList.add(order.photographer)
		allowedUsersList.add(order.client)
		
		if (allowedUsersList.contains(springSecurityService.getCurrentUser())) {
			out << body()
		}
		else {
			out << "No tiene permisos para ver la pagina"
		}
	}
	
	def isLoggedInUser = { attrs, body ->
		User user = User.get(attrs.userId)
		if (user == springSecurityService.getCurrentUser()) {
			out << body()
		}
	}
	
	def isNotLoggedInUser = { attrs, body ->
		User user = User.get(attrs.userId)
		if (user != springSecurityService.getCurrentUser()) {
			out << body()
		}
	}
}
